//
//  UIWindow+YTX.m
//  p4
//
//  Created by yang xincheng on 15/1/5.
//  Copyright (c) 2015年 me.yang-yuxin. All rights reserved.
//

#import "UIViewController+Visible.h"

@implementation UIViewController (Visible)

+ (UIViewController *)visibleViewController
{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [UIViewController getVisibleViewControllerFrom:rootViewController];
}

+ (UIViewController *)getVisibleViewControllerFrom: (UIViewController *)viewController
{
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabController = (UITabBarController *)viewController;
        return [UIViewController getVisibleViewControllerFrom:tabController.selectedViewController];
    }
    else if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navController = (UINavigationController *)viewController;
        return [UIViewController getVisibleViewControllerFrom:navController.visibleViewController];
    }
    if (viewController.presentedViewController) {
        UIViewController *presentedController = viewController.presentedViewController;
        return [UIViewController getVisibleViewControllerFrom: presentedController];
    }
    return viewController;
}

+ (UIViewController *)presentingViewController
{
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIViewController *result = window.rootViewController;
    while (result.presentedViewController) {
        result = result.presentedViewController;
    }
    return result;
}

@end
